
package HumanCentredSystemDesign;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author Chris, Martin, Dom
 */

public class DischargeManager extends LibraryCirculations {

        Item myItem;
        
    public void dischargeCopy(String dewey) {

            try
            {
                myLoan = getLoanFromDewey(dewey);
            }
            catch(Exception err)
            {
                String errString = "Can not get associated loan from the Dewey ID: " + err.toString();
                AlertWindow aw = new AlertWindow(errString);
                aw.setVisible(true);
                System.out.println(errString);
                return;
            }

            myBorrower = getBorrower(myLoan.getLibraryMemberID(), "", "", "").get(0);
            myCopy = getCopyFromDewey(dewey); 
            myItem = getItemFromCopy(myCopy);

            if (validateDischarge(myBorrower, myCopy) == true)
            {   
                this.chargeFine(myLoan);
                myLoan.removeLoanFromDatabase();
            }
        }


     public boolean validateDischarge(Borrower b, Copy c){
          boolean myBool = false;
          if (c.onLoan() ==true)
          {
             myBool = true;
          }
          else
          {
             myBool = false;
             AlertWindow aw = new AlertWindow("This copy has not been loaned.");
             aw.setVisible(true);
          }

          return myBool;
        }

    public void chargeFine(Loan _loan) {

        Date issueDate = _loan.getIssueDate();
        Date today = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String todayString = formatter.format(today);
        AlertWindow aw;
        String message = "Loan has been discharged";

        if(_loan.isOverdue()){
               try{
                   Date today2 = formatter.parse(todayString);
                   long timeDiffMs = today2.getTime() - issueDate.getTime();
                   int timeDiffSec = (int) (timeDiffMs/1000);
                   int timeDiffMin = timeDiffSec/60;
                   int timeDiffHour = timeDiffMin/60;
                   int timeDiffDay = timeDiffHour/24;

                   int daysOverdue = timeDiffDay - _loan.getLoanPeriod();
                   message = "A fine of £"+daysOverdue+".00 is due. Confirm to pay fines and discharge loan";
               }
               catch(ParseException ex){
                   System.out.println(ex.toString());
               }

               aw = new AlertWindow(message);
               aw.setVisible(true);
        }

    }

	
}
